package test.functionQuery.functionsort;

import java.io.IOException;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.lucene.index.AtomicReaderContext;
import org.apache.lucene.queries.function.FunctionValues;
import org.apache.lucene.queries.function.ValueSource;
import org.apache.lucene.queries.function.docvalues.FloatDocValues;

import com.hunteron.common4s.jdk.string.str.StringTools;

public class FunctionSortValueSource extends ValueSource {
    public String functionName;
    public ValueSource field;
    
    public FunctionSortValueSource(String functionName, ValueSource field) {
        super();
        this.functionName = functionName;
        this.field = field;
    }

    @Override
    public FunctionValues getValues(@SuppressWarnings("rawtypes") Map context, AtomicReaderContext readerContext) throws IOException {
        final FunctionValues fieldVals =  field.getValues(context, readerContext);
        return new FloatDocValues(this) {
            @Override
            public float floatVal(int doc) {
                String fieldValues = fieldVals.strVal(doc);
                return functionSortValueWithString(fieldValues, functionName);
            }

            @Override
            public String toString(int doc) {
                return description() + " : " + functionName;
            }
        };
    }
    
    public float functionSortValueWithString(String fieldValue, String functionNames) {
        if(StringUtils.isBlank(fieldValue)) {
            return 0f;
        }
        String[] values = functionNames.split("\\s+");
        float total = 0;
        for(String v : values) {
            total += functionSortValue(fieldValue, v);
        }
        return total;
    }

    public float functionSortValue(String fieldValue, String functionName) {
        int indexLeft = fieldValue.indexOf(functionName);
        if(indexLeft < 0) {
            return 0;
        }
        int indexStart = fieldValue.indexOf(":", indexLeft);
        if(indexStart < 0) {
            return 0;
        }
        int indexEnd = fieldValue.indexOf(",", indexStart);
        if(indexEnd > indexStart) {
            String temp = fieldValue.substring(indexStart + 1, indexEnd);
            return StringTools.getFloat(temp, 0F);
        }
        return 0;
    }

    @Override
    public boolean equals(Object o) {
        return false;
    }

    @Override
    public int hashCode() {
        return 0;
    }

    @Override
    public String description() {
        return "functionSort";
    }

}
